package com.mission.schedule.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.CalenderNoteBean;
import com.mission.schedule.bean.CalenderNoteSynBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.utils.SharedPrefUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

/**
 * 下载普通日程
 * Created by liwei on 2017/4/7.
 */

public class DownCalenderNoteService extends Service {


    App application = App.getDBcApplication();
    SharedPrefUtil sharedPrefUtil = null;
    String UserId = "";
    List<CalenderNoteBean.PageBean.ItemsBean> calenderBeanlist;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        sharedPrefUtil = new SharedPrefUtil(getApplication(), ShareFile.USERFILE);
        UserId = sharedPrefUtil.getString(getApplicationContext(), ShareFile.USERFILE, ShareFile.USERID, "");
        RequestParams params = new RequestParams();
        params.addBodyParameter("uid", UserId);
        params.addBodyParameter("changeTime", App.getDBcApplication().getCalenderNoteDataDownTime().isEmpty() ? "2017-10-01" :
                App.getDBcApplication().getCalenderNoteDataDownTime().replace("T"," "));
        params.addBodyParameter("nowpage", "1");
        params.addBodyParameter("pageNum", "2000");
        new HttpUtils(10000).send(HttpMethod.POST, URLConstants.日程清单下载, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    try {
                        Gson gson = new Gson();
                        CalenderNoteBean bean = gson.fromJson(responseInfo.result, CalenderNoteBean.class);
                        if (bean.status == 0) {
                            sharedPrefUtil.putString(getApplication(),
                                            ShareFile.USERFILE, ShareFile.UPDATENOTESETTIME, bean.downTime.replace('T', ' '));
                            List<CalenderNoteBean.PageBean.ItemsBean> itemsBeanList = bean.page.items;

                            if (itemsBeanList != null) {
                                for (CalenderNoteBean.PageBean.ItemsBean itemsBean : itemsBeanList) {
                                    App.getDBcApplication().saveCalederNoteDetailData(itemsBean);
                                }
                            }
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
        RequestParams params1 = new RequestParams();
        params1.addBodyParameter("cUid", UserId);
        params1.addBodyParameter("changeTime", App.getDBcApplication().getCalenderNoteDataDownTime().isEmpty() ? "2017-10-01" :
                App.getDBcApplication().getCalenderNoteDataDownTime().replace("T"," "));
        params1.addBodyParameter("nowpage", "1");
        params1.addBodyParameter("pageNum", "2000");
        new HttpUtils(10000).send(HttpMethod.POST, URLConstants.重复清单下载, params1, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    try {
                        Gson gson = new Gson();
                        CalenderNoteBean bean = gson.fromJson(responseInfo.result, CalenderNoteBean.class);
                        if (bean.status == 0) {
                            sharedPrefUtil.putString(getApplication(),
                                    ShareFile.USERFILE, ShareFile.UPDATENOTESETTIME, bean.downTime.replace('T', ' '));
                            List<CalenderNoteBean.PageBean.ItemsBean> itemsBeanList = bean.page.items;

                            if (itemsBeanList != null) {
                                for (CalenderNoteBean.PageBean.ItemsBean itemsBean : itemsBeanList) {
                                    App.getDBcApplication().saveCalederNoteDetailData(itemsBean);
                                }
                            }
                        }
                    } catch (JsonSyntaxException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
        return super.onStartCommand(intent, flags, startId);
    }

    private void uploadCalendernote() {
        JSONObject listjsonObject = new JSONObject();
        JSONArray listjsonArray = new JSONArray();
        try {
            for (CalenderNoteBean.PageBean.ItemsBean bean : calenderBeanlist) {
                JSONObject js = new JSONObject();
                js.put("id", bean.id);
                js.put("titleId", bean.titleId);
                js.put("uid", bean.uid);
                js.put("titles", bean.titles);
                js.put("imgPath", bean.imgPath);
                js.put("imgUrl", bean.imgUrl);
                js.put("shareUrl", bean.shareUrl);
                js.put("contents", bean.contents);
                js.put("nums", bean.nums);
                js.put("style", bean.style);
                js.put("endstate", bean.endstate);
                js.put("lType", bean.ltype);
                js.put("orderId", bean.orderId);
                js.put("createTime", bean.createTime);
                js.put("changeTime", bean.changeTime);
                js.put("cpath", bean.cpath);
                js.put("curl", bean.curl);
                js.put("sdesc", bean.sdesc);
                js.put("localIds", bean.localIds);
                js.put("remark", bean.remark);
                js.put("remark1", bean.remark1);
                js.put("remark2", bean.remark2);
                js.put("remark3", bean.remark3);
                js.put("remark4", bean.remark4);
                js.put("remark5", bean.remark5);
                js.put("remark6", bean.remark6);
                js.put("updateState", bean.id < 0 ? 1 : App.getDBcApplication().getCalenderNoteDetailState(bean.titleId, UserId, bean.id));
                listjsonArray.put(js);
            }
            if (calenderBeanlist.size() > 0) {
                listjsonObject.put("timetable", listjsonArray);
            }


            HttpUtils httpUtils = new HttpUtils(10000);
            RequestParams params = new RequestParams();
            params.addBodyParameter("data", listjsonObject == null ? "" : listjsonObject.toString());
            httpUtils.send(HttpMethod.POST, URLConstants.日程清单同步数据, params,
                    new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException e, String msg) {
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            if (!TextUtils.isEmpty(responseInfo.result)) {
                                Gson gson = new Gson();
                                CalenderNoteSynBean bean = gson.fromJson(responseInfo.result, CalenderNoteSynBean.class);
                                if (bean.status == 0) {
                                    List<CalenderNoteSynBean.ListBean> listBeanList = bean.list;


                                    for (CalenderNoteSynBean.ListBean listBean : listBeanList) {
                                        if (listBean.dataState == 1) {//新增
                                            if (listBean.state == 0) {//成功
                                                //修改id和状态值
                                                App.getDBcApplication().updateCalenderNoteDetailId(listBean.id, listBean.calendId, UserId);
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.calendId, UserId, 0, true);
                                            } else if (listBean.state == 1) {//失败  可以不操作,但是避免意外
                                                //更改状态为1
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, UserId, 1, true);
                                            } else if (listBean.state == 2) { //异常
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, UserId, -1, true);
                                            }
                                        } else if (listBean.dataState == 2) {//修改
                                            if (listBean.state == 0) {//成功
                                                //修改该id状态值
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, UserId, 0, true);
                                            } else if (listBean.state == 1) {//失败
                                                //更改状态为2
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, UserId, 2, true);
                                            } else if (listBean.state == 2) { //异常
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, UserId, -1, true);
                                            }
                                        } else if (listBean.dataState == 3) {//删除
                                            if (listBean.state == 0) {//成功
                                                //删除该id的清单
                                                App.getDBcApplication().deleteCalenderNoteTitledetailData(listBean.id, UserId, true);
                                            } else if (listBean.state == 1) {//失败
                                                //更改状态为3
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, UserId, 3, true);
                                            } else if (listBean.state == 2) { //异常
                                                App.getDBcApplication().updateCalenderNoteDetailState("", listBean.id, UserId, -1, true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
